package com.soulkun.smarthome.ui.main.personal.viewmodel

import androidx.databinding.ObservableArrayList
import androidx.lifecycle.ViewModel
import com.soulkun.smarthome.logic.repository.ApiRepository
import com.soulkun.smarthome.logic.vo.FamilyMessageHistoryItemVO
import com.soulkun.smarthome.logic.vo.FamilyMessageHistoryVO
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import soulkun.library.mvvm.adapter.clearAndAddAll
import soulkun.library.utils.logE
import soulkun.library.utils.time.DateUtils
import soulkun.library.utils.time.TimeUtils
import java.util.*

class AppMainPersonalMessageFamilyViewModel : ViewModel() {

    val familyMessageList = ObservableArrayList<FamilyMessageHistoryVO>()

    fun getFamilyMessageList() = ApiRepository.getFamilyMessageList(this) {
        val list = arrayListOf<FamilyMessageHistoryVO>()
        withContext(Dispatchers.Default) {
            var date = 0L
            val sortedList = it.data.sortedBy{familyMessageDTO -> familyMessageDTO.at }.asReversed() //时间降序
            sortedList.forEach(action = { familyMessageDTO ->
                val messageDate = DateUtils.timestampToDate(familyMessageDTO.at).time
                if (date != messageDate) {
                    list.add(FamilyMessageHistoryVO(messageDate, ObservableArrayList()))
                    date = messageDate
                }
                list.last().messageList.add(
                    FamilyMessageHistoryItemVO(
                        familyMessageDTO.title,
                        if (familyMessageDTO.title != "删除家庭") {
                            String.format(
                                familyMessageDTO.content,
                                familyMessageDTO.activeUserName,
                                familyMessageDTO.passiveUserName,
                                familyMessageDTO.familyName
                            )
                        } else {
                            String.format(
                                familyMessageDTO.content,
                                familyMessageDTO.activeUserName,
                                familyMessageDTO.familyName
                            )
                        },
                        TimeUtils.dateToStringWithFormat(
                            Date(familyMessageDTO.at.time),
                            TimeUtils.TIME_FORMAT
                        ) ?: ""
                    )
                )
            })
        }
        withContext(Dispatchers.Main) {
            familyMessageList.clearAndAddAll(list)
        }

    }

}